<?php
require_once("initialize.php");
class UserController{
    
    
    public $user;
    public $login;
    public $location;

    
    // Finds the info from a Login, Comment and User object on a current id
    public function showUserInfo($userid){
       $comment = new Comment();
       $login  = new Login();
       $userobject = User::find_by_id($userid);
       $commentsobject = $comment->Find_Comments_On_User($userid);
       $loginobject  = $login->find_Login_by_userid($userid);
       return array($userobject,$commentsobject,$loginobject);
    }
    
    // Recieves new user information and saves it in the databse. Returns error message if any of the values is invalid
    public function changeUserInfo($f,$l,$u,$year,$sex,$zipcode,$userid){
        $user = new User();
        $user = $user->find_by_id($userid);
        $m = "";
      
        
        // Checks for valid input for firstname.
        if(isset($f) && !empty($f) && $f!=""){
            
            $user->firstname = $f;
            
        }else{
            $m .=  "Fornavn ikke satt</br>";
            
        }
        
        // Checks for valid input for lastname.
        if(isset($l) && !empty($l) && $l!=""){
            $user->lastname = $l;
        }else{
            
            $m .= "Etternavn ikke satt</br>";
            
        }
        
        // Checks for valid input for firstname.
        if(isset($u) && !empty($u) && (!$user->usernameExists($u)) || $user->find_by_id($user->id)->username == $u){
            $user->username = $u;
        }else{
           $m .=  "Brukernavn ikke satt eller eksisterer fra før</br>"; 
        }
       
        if(isset($year) && !empty($year) && $year < date("Y", time())-10 && $year > 1900 ){
            $user->yearborn =$year;
        }else{
           $m .=  "Født år ikke satt eller du er for ung.</br>"; 
        }
        
        if(isset($sex) || !empty($sex)){
             $user->sex = $sex;
        }else{
           $m .= "Kjønn ikke satt.</br>"; 
        }
        
        if(isset($zipcode) && !empty($zipcode) && strlen($zipcode)==4 && Location::zipcodeExists($zipcode)) {
             $user->zipcode = $zipcode;
             
        }else{
           $m .=  "Ugyldig postnummer.</br>"; 
           
        }
        
        if(isset($userid) || !empty($user)){
            
             $user->id = $userid;
        }
        
        if($m != "" && !empty($m)){
            return $m;
        
        }
        else{
            $user->build($user);
        }
            
    }
   
    // Changes the password of an user, checks if the old password matches the old one and the two new inputed password matches
    public function changeLoginPass($userid,$oldpassword,$newpassword,$newpassword1){
        //changes loginpassword
        $login = new Login();
        $loginarray = $login->find_Login_by_userid($userid);
        $login =$loginarray[0];
        $p = sha1($oldpassword);
        if(Login::authUserId($userid, $p)){
            
        if($newpassword!=""){
           // new password placed 
            
           if($newpassword==$newpassword1){
               //password match
               if(preg_match("#.*^(?=.{6,20})(?=.*[a-å])(?=.*[A-Å])(?=.*[0-9]).*$#", $newpassword)){
                   //password strong enough
                   $newp = sha1($newpassword);
                   $login->password = $newp;
                   $login->build($login);
                  
               }else{
                   return "For svakt passord, passord må inneholde tall, stor bokstav og minimum lengde på 6.";
               }
           }else{
               return "Passordene du har skrevet inn stemmer ikke overens";
           }
        }else{
            return "nytt Passord kan ikke være blankt";
        }
        
       }else{
           return "Gammelt passord stemmer ikke";
       }
    }
    
    //Changes the login information on an user
    public function changeLoginInfo($userid = 0, $email = "", $oldpassword = ""){
        // This changes the data stored in login model.
        $login = new Login();
        $loginarray = $login->find_Login_by_userid($userid);
        $login =$loginarray[0];
        $m = "";
       if($email!=""){
           //something is writen
           
           if(Login::existingEmail($email) == null  || $login->email == $email){
               //email doesent exist
               if($oldpassword!=""){
                   //password has been written
                    $p = sha1($oldpassword);
                    if(Login::authUserId($userid, $p)){
                        //user authenticated now change email
                        $login->email = $email;
                        $login->build($login);
                        return "Endringer utført!";
                
                    }else{
                        $m .= "Feil Passord</br>";
               
                }
                }else{
                    $m .=  "Passord ikke satt</br>"; 
         }
         }else{
            $m .= "Epost eksisterer fra før</br>";
      }
      }else{
            $m .= "Email ikke satt</br>";
            
            echo $m;

       }
       
       return $m;
    }
    
    // Creates and registers a new user 
    public function newUser($firstname, $gender, $lastname, $username, $email, $zip, $birthdate, $pw, $pw2){
        
        $user       = new User();
        $ulregister = new Login();
        $m          = "";
        
        if(isset($firstname) && !empty($firstname) && $firstname!=""){
            
            $user->firstname = $firstname;
        }
        else{
            $m .=  "Fornavn ikke satt</br>";
        }
        
        // Checks for valid input for lastname.
        if(isset($lastname) && !empty($lastname) && $lastname!=""){
            
            $user->lastname = $lastname;
        }
        else{
            $m .= "Etternavn ikke satt</br>";
        }
        
        if(isset($birthdate) && !empty($birthdate) && $birthdate < date("Y", time())-10 && $birthdate > 1900 ){
            
            $user->yearborn    = $birthdate;
        }
        else{
           $m .=  "Født år ikke satt eller du er for ung.</br>"; 
        }
        
        if(!$user->usernameExists($username) && $username != ""){
                
                    $user->username    = $username;
                    
        }
        else{
            $m .= "Brukernavn er tomt eller eksisterer fra før<br>";
        }
        
        
        if(!Login::existingEmail($email) && preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)){
        
               $ulregister->email = $email;
               
        }
        else{
            
            $m .=  "Mailadressen er enten registert eller skrevet feil. <br>";
        }
        
        if($gender == 'male' || $gender == 'female'){
            
            $user->sex         = $gender;
        }
        else{
            $m .= 'Du må velge kjønn!<br>';
        }
    
        if($zip != "" && Location::zipcodeExists($zip)){
                
            $user->zipcode     = $zip;
        }
        else{
            $m .= "Postnummeret eksister ikke<br>";
        }
        
         
        
         
        
        if($pw == $pw2){
            
            if (preg_match("#.*^(?=.{6,20})(?=.*[a-å])(?=.*[A-Å])(?=.*[0-9]).*$#", $pw)){

                $ulregister->password       = sha1($pw);
             



            }
            else{
                $m .=  "Passordet ditt er for svakt, vennligst bruk minimum 6 tegn, Minimum en stor bokstav og tall<br>";
            }
    
    
        }else{
            $m .= "Passordene du har skrevet inn stemmer ikke overens.<br>";
        }
         
        if($m =="" && empty($m)){
                
                $activtedstring             = $ulregister->createaAString($email, $ulregister->password);
                $ulregister->activatestring = $activtedstring;
                $user->save();
                $userid                     = $user->id;
                $ulregister->user_id        = $userid;

                $ulregister->save();
                /*
                $to = $uregisteremail;
                $subject = "Ny Bruker i Forbrukermakt.com";
                $message = "Velkommen som ny bruker hos forbrukermakt.com, for å kunne bruke din konto er du nødt til å aktivere denne, det gjør du 
                    på følgende side= http://localhost/aktivering.php?activ={$activtedstring}";
                $from = "noreply@flowershopfucker.no";
                $headers = "From:" . $from;
                mail($to,$subject,$message,$headers);
                */
                redirect_to("/public/activation.php?activ={$activtedstring}");
            }
            else{
                return $m;

            }
           
    }   
    
    // Authenticates a user by username and password
    public function authUser($sloginusername,$sloginpassword){
         $sloginpassword1 = sha1($sloginpassword); // creates a crypted variable for the password

	$found_user = Login::auth($sloginusername, $sloginpassword1); /// Check database to see if username/password exist.
	

  if ($found_user) {// if the user exist do make a login object and a user object, and store theese in the database 
      
      $uactivedo = new Login();
      $ulogins = Login::find_all();
      

// This FOREACHloop get runs through all the login object until it finds a wich matches the email,then we
// checks that the activeted variable is set to one. If so you can log inn. If not you get an
// error message of that you have not activted your account.
      

                foreach($ulogins as $uactivedo){
                  if ($uactivedo->email == $sloginusername){

                      $uactiveone = $uactivedo->activated ;
                      $auserid= $uactivedo->id;

                  }
                }

                 if($uactiveone==1){ // Checks if your account is activeted, if so u get get loggin in by session and redirected to admin area.
                                $session = new Session();
                                $session->login($found_user);

                    redirect_to("view/admin/index.php");
                }else{
                    return "bruker ikke aktivert!";
     }
  } else {
    // username/password combo was not found in the database
    return "Username/password combination incorrect.";
  }
  
    }
    
    // Method activates an account for the current user (Username, password)
    public function activateAccount($aloginusername,$aloginpassword,$activeget){
        // Check database to see if username/password exist.
          $aloginpassword1 = sha1($aloginpassword);
	$found_user = Login::auth($aloginusername, $aloginpassword1);
	
  if($found_user) {
 //login success
     $activedo = new Login();
      $activatedcheck = $activedo->createaAString($aloginusername, $aloginpassword1);
      if($activatedcheck==$activeget){
          //activate account if right string is in $_GET['activ']
  
            $logins = Login::find_all();
      
                    foreach($logins as $activedo){

                      if  ($activedo->email == $aloginusername){
                          $activeone = 1;
                          $activedo->activated = $activeone;
                          $auserid= $activedo->id;
                          $activedo->save();
                      }
                    }
                $session = new Session();
                $session->login($found_user);
		
                $_SESSION['sessionuserid']=$auserid;
                
    redirect_to("view/admin/index.php");
      }
  } else {
    // username/password combo was not found in the database
    return "Username/password combination incorrect.";
  }
  


        
    }
    public function searchUser($kw){
        $this->user = new User();
        return $this->user->searchUser($kw);
    }
    
    
}
$user_controller = New UserController();
?>
